const app = require('express')();
const bodyParser = require('body-parser');
const mammoth = require("mammoth");
const nodemailer = require('nodemailer')
const {
  updateExportLog,
  updateCheckMailLog,
  updateSendMailLog,
  exportJson2Excel
} = require('./tools')
require('./timer')
const fs = require('fs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));

const port = 8868
app.listen(port, () => {
  console.log(`http://localhost:${port}`)
})

// 配置跨域
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*")
  // res.header("Access-Control-Allow-Credentials", true)
  // 允许的域 只有一个则可以使用cookie
  // 若为 * 多个 浏览器出于安全考虑 不能使用cookie
  res.header("Access-Control-Allow-Headers", "Content-Type")
  // res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS')
  // res.setHeader('Content-Type', 'application/json')
  // res.header("Content-Type", "application/json;charset=utf-8")
  next();
})

app.get('/', (req, res) => {
  res.send('hello')
})

// 校验邮箱和授权码
app.post('/checkMail', async (req, res) => {
  let {
    mail,
    code,
    host,
    port,
    data
  } = req.body.data

  let transporter = nodemailer.createTransport({
    host: host,
    port: port,
    secure: false,
    auth: {
      user: mail,
      pass: code
    }
  })
  await transporter.sendMail({
    from: `邮箱校验成功！<${mail}>`,
    to: `<${mail}>`,
    text: ''
  }, (err, info) => {
    try {
      if (err) {
        updateCheckMailLog(data, '校验失败')
        res.send({
          message: '校验失败',
          code: 0,
          error: err
        })
      }
      updateCheckMailLog(data, '校验成功')
      res.send({
        message: '校验成功',
        code: 1
      })
    } catch {}
  })
})


// 接受二进制流，并转为Word暂存到服务端
app.post('/upload', (req, res) => {
  let buffer = new Buffer.from(req.body.data.buffer)
  let {
    info,
    data
  } = req.body.data
  let path = `./data/${info.title}.docx`
  fs.writeFileSync(path, buffer);
  mammoth.convertToHtml({
    path
  }).then(async result => {
    await sendMail(info, path, result.value + `<pre style="font-size: 12px; font-family: 'sans-serif'">------------------------\n${info.signature}</pre>`)
    updateSendMailLog(data, '发送成功')
    res.send('邮件发送成功')
  }).catch(() => {
    updateSendMailLog(data, '发送失败')
    res.send('邮件发送失败')
  })
})

// 发送邮件函数
async function sendMail(info, filePath, htmlTemplate) {
  const to = info.toMail // 接受者邮箱
  const cc = info.cc.split(/,|，/).map(val => '<' + val.trim() + '>').join(',')
  let transporter = nodemailer.createTransport({
    host: info.host,
    port: info.port,
    secure: false,
    auth: {
      user: info.fromMail, // 发送者邮箱
      pass: info.mailCode // 邮箱授权码
    }
  })
  // let html = (htmlTemplate.match(/(?<=日）<\/p><p><br \/><\/p>).*/) || [''])[0]; // 去除大标题和日期
  let html = htmlTemplate.replace(/\s{5}/g, '&nbsp;'.repeat(5)); /* 将连续空格替换成 &nbsp; 用于在邮件正文区显示缩进 */
  await transporter.sendMail({
    from: `${info.senderNickName}<${info.fromMail}>`, //! 发件人 固定格式 xxx<邮箱号>
    to: `<${to}>`, //! 收件人 固定格式 xxx<邮箱号> 多个以 "," 分隔
    cc: cc + ',' + info.fromMail, //! 抄送 邮箱号，多个以 "," 分隔
    subject: info.title, // 标题
    // text: info.title, // 邮件预览文字
    /* 正文 */
    html: html,
    attachments: [{
      filename: `${info.title}.docx`, // 附件名
      path: filePath // 附件路径
    }]
  })
  try {
    fs.rmSync(filePath)
  } catch {}
}

// 记录使用导出功能的日志
app.post('/recordExportWord', (req, res) => {
  updateExportLog(req.body.data)
  res.send({
    message: true
  })
})

// 获取日志记录信息
app.get('/getRecordData', (req, res) => {
  res.send(JSON.parse(fs.readFileSync('./data/user.json', {
    encoding: 'utf-8'
  })))
})
